package org.topteam.oschat.socket;

import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.handlers.PathHandler;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;

import java.io.IOException;

import javax.servlet.ServletException;

import org.apache.log4j.Logger;
import org.topteam.oschat.security.AuthServlet;
import org.xnio.ByteBufferSlicePool;
import org.xnio.OptionMap;
import org.xnio.Xnio;

public class WebSocketServer {

	private Logger logger = Logger.getLogger(WebSocketServer.class);

	private String host;
	private int port;
	private String path = "/";

	private Undertow server;

	public void start() {
		logger.info("Undertow starting[" + host + ":" + port + path + "]");
		PathHandler pathHandler = Handlers.path();
		server = Undertow.builder().addHttpListener(port, host)
				.setHandler(pathHandler).build();
		server.start();
		final ServletContainer container = ServletContainer.Factory
				.newInstance();

		DeploymentInfo builder;
		try {
			builder = new DeploymentInfo()
					.setClassLoader(WebSocketServer.class.getClassLoader())
					.setContextPath("/")
					.addServlet(
							Servlets.servlet("auth", AuthServlet.class)
									.addMapping("/auth"))
					.addServletContextAttribute(
							WebSocketDeploymentInfo.ATTRIBUTE_NAME,
							new WebSocketDeploymentInfo()
									.setBuffers(
											new ByteBufferSlicePool(100, 1000))
									.setWorker(
											Xnio.getInstance().createWorker(
													OptionMap.EMPTY))
									.addEndpoint(WebSocketEndpoint.class))
					.setDeploymentName("chat.war");
			DeploymentManager manager = container.addDeployment(builder);
			manager.deploy();
			pathHandler.addPrefixPath(path, manager.start());
		} catch (IllegalArgumentException e) {
			logger.error("Undertow start failed", e);
		} catch (IOException e) {
			logger.error("Undertow start failed", e);
		} catch (ServletException e) {
			logger.error("Undertow start failed", e);
		}

	}

	public void close() {
		server.stop();
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

}
